package top.forlenet.controller;



import org.apache.commons.beanutils.BeanUtils;
import top.forlenet.common.CommonResult;
import top.forlenet.common.MyException;
import top.forlenet.param.RegisterParam;
import top.forlenet.service.UserService;
import top.forlenet.service.impl.UserServiceImpl;
import top.forlenet.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        RegisterParam param = new RegisterParam();
        try {
            BeanUtils.populate(param, parameterMap);
            UserService userService = new UserServiceImpl();
            userService.register(param);

            response.getWriter().write(JsonUtils.bean2json(CommonResult.success()));

        } catch (MyException e) {
            response.getWriter().write(JsonUtils.bean2json(CommonResult.error(e.getMsg())));
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(JsonUtils.bean2json(CommonResult.error("未知异常")));
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
